/**
 * Copyright (c) 2013-2022 Nikita Koksharov
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.redisson;

import org.redisson.api.*;
import org.redisson.client.codec.LongCodec;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.handler.State;
import org.redisson.client.protocol.RedisCommand;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.client.protocol.decoder.MapEntriesDecoder;
import org.redisson.client.protocol.decoder.MultiDecoder;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.misc.CompletableFutureWrapper;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;

/**
 * @author Nikita Koksharov
 */
public class RedissonRateLimiter extends RedissonExpirable implements RRateLimiter {

    public RedissonRateLimiter(CommandAsyncExecutor commandExecutor, String name) {
        super(commandExecutor, name);
    }

    String getPermitsName() {
        return suffixName(getRawName(), "permits");
    }

    String getClientPermitsName() {
        return suffixName(getPermitsName(), getServiceManager().getId());
    }

    String getValueName() {
        return suffixName(getRawName(), "value");
    }

    String getClientValueName() {
        return suffixName(getValueName(), getServiceManager().getId());
    }

    /**
     * 尝试设置限流模式和速率。
     */
    @Override
    public boolean trySetRate(RateType type, long rate, long rateInterval, RateIntervalUnit unit) {
        return get(trySetRateAsync(type, rate, rateInterval, unit));
    }

    @Override
    public RFuture<Boolean> trySetRateAsync(RateType type, long rate, long rateInterval, RateIntervalUnit unit) {
        return commandExecutor.evalWriteNoRetryAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
                //         hsetnx redisson_rate_limiter rate     10
                //         hsetnx reidsson_rate_limiter interval 1000
                //  retrun hsetnx redisson_rate_limiter type     PER_CLIENT
                "redis.call('hsetnx', KEYS[1], 'rate', ARGV[1]);"
                        + "redis.call('hsetnx', KEYS[1], 'interval', ARGV[2]);" +
                        "return redis.call('hsetnx', KEYS[1], 'type', ARGV[3]);", Collections.singletonList(getRawName()), rate, unit.toMillis(rateInterval), type.ordinal());
    }

    /**
     * 设置限流模式和速率。
     */
    @Override
    public void setRate(RateType type, long rate, long rateInterval, RateIntervalUnit unit) {
        get(setRateAsync(type, rate, rateInterval, unit));
    }

    @Override
    public RFuture<Void> setRateAsync(RateType type, long rate, long rateInterval, RateIntervalUnit unit) {
        return commandExecutor.evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
                // local valueName   = {redisson_rate_limiter}:value
                // local permitsName = {redisson_rate_limiter}:permits
                // if (type.ordinal() == 1) then
                //    valueName   = {redisson_rate_limiter}:value:client_id
                //    permitsName = {redisson_rate_limiter}:permits:client_id
                // end
                // hset redisson_rate_limiter rate 10
                // hset redisson_rate_limiter interval 1000
                // hset redisson_rate_limiter type PER_CLIENT
                // hdel valueName permitsName
                "local valueName = KEYS[2];" + "local permitsName = KEYS[4];" + "if ARGV[3] == '1' then " + "    valueName = KEYS[3];" + "    permitsName = KEYS[5];" + "end " + "redis.call('hset', KEYS[1], 'rate', ARGV[1]);" + "redis.call('hset', KEYS[1], 'interval', ARGV[2]);" + "redis.call('hset', KEYS[1], 'type', ARGV[3]);" + "redis.call('del', valueName, permitsName);", Arrays.asList(getRawName(), getValueName(), getClientValueName(), getPermitsName(), getClientPermitsName()), rate, unit.toMillis(rateInterval), type.ordinal());
    }


    /**
     * 尝试立即获取一个许可。
     */
    @Override
    public boolean tryAcquire() {
        return tryAcquire(1);
    }

    @Override
    public boolean tryAcquire(long permits) {
        return get(tryAcquireAsync(RedisCommands.EVAL_NULL_BOOLEAN, permits));
    }


    @Override
    public RFuture<Boolean> tryAcquireAsync() {
        return tryAcquireAsync(1L);
    }


    @Override
    public RFuture<Boolean> tryAcquireAsync(long permits) {
        return tryAcquireAsync(RedisCommands.EVAL_NULL_BOOLEAN, permits);
    }


    /**
     * 强制获取一个许可，如果立即不可用则等待
     */
    @Override
    public void acquire() {
        get(acquireAsync());
    }

    @Override
    public void acquire(long permits) {
        get(acquireAsync(permits));
    }

    @Override
    public RFuture<Void> acquireAsync() {
        return acquireAsync(1);
    }

    @Override
    public RFuture<Void> acquireAsync(long permits) {
        CompletionStage<Void> f = tryAcquireAsync(permits, -1, null).thenApply(res -> null);
        return new CompletableFutureWrapper<>(f);
    }

    @Override
    public boolean tryAcquire(long timeout, TimeUnit unit) {
        return get(tryAcquireAsync(timeout, unit));
    }

    @Override
    public RFuture<Boolean> tryAcquireAsync(long timeout, TimeUnit unit) {
        return tryAcquireAsync(1, timeout, unit);
    }

    @Override
    public boolean tryAcquire(long permits, long timeout, TimeUnit unit) {
        return get(tryAcquireAsync(permits, timeout, unit));
    }

    @Override
    public RFuture<Boolean> tryAcquireAsync(long permits, long timeout, TimeUnit unit) {
        long timeoutInMillis = -1;
        if (timeout >= 0) {
            timeoutInMillis = unit.toMillis(timeout);
        }
        CompletableFuture<Boolean> f = tryAcquireAsync(permits, timeoutInMillis);
        return new CompletableFutureWrapper<>(f);
    }

    private CompletableFuture<Boolean> tryAcquireAsync(long permits, long timeoutInMillis) {
        long s = System.currentTimeMillis();
        RFuture<Long> future = tryAcquireAsync(RedisCommands.EVAL_LONG, permits);
        return future.thenCompose(delay -> {
            if (delay == null) {
                return CompletableFuture.completedFuture(true);
            }

            if (timeoutInMillis == -1) {
                CompletableFuture<Boolean> f = new CompletableFuture<>();
                getServiceManager().getGroup().schedule(() -> {
                    CompletableFuture<Boolean> r = tryAcquireAsync(permits, timeoutInMillis);
                    commandExecutor.transfer(r, f);
                }, delay, TimeUnit.MILLISECONDS);
                return f;
            }

            long el = System.currentTimeMillis() - s;
            long remains = timeoutInMillis - el;
            if (remains <= 0) {
                return CompletableFuture.completedFuture(false);
            }

            CompletableFuture<Boolean> f = new CompletableFuture<>();
            if (remains < delay) {
                getServiceManager().getGroup().schedule(() -> {
                    f.complete(false);
                }, remains, TimeUnit.MILLISECONDS);
            } else {
                long start = System.currentTimeMillis();
                getServiceManager().getGroup().schedule(() -> {
                    long elapsed = System.currentTimeMillis() - start;
                    if (remains <= elapsed) {
                        f.complete(false);
                        return;
                    }

                    CompletableFuture<Boolean> r = tryAcquireAsync(permits, remains - elapsed);
                    commandExecutor.transfer(r, f);
                }, delay, TimeUnit.MILLISECONDS);
            }
            return f;
        }).toCompletableFuture();
    }

    /**
     * 尝试异步获取许可。
     * <p>
     * 使用Lua脚本在Redis中执行，以确保获取许可的逻辑的原子性。
     * 此方法用于实现速率限制功能，确保不会超过预定义的速率。
     *
     * @param command Redis命令执行器。
     * @param value   请求的许可数量。
     * @return 一个未来的许可结果。
     */
    private <T> RFuture<T> tryAcquireAsync(RedisCommand<T> command, Long value) {
        // 生成一个随机字节数组，用于在许可中唯一标识请求者
        byte[] random = getServiceManager().generateIdArray();

        // 使用命令执行器异步执行Lua脚本
        return commandExecutor.evalWriteAsync(getRawName(), LongCodec.INSTANCE, command,
                // 从Redis的hash中获取速率、间隔和类型信息，确保速率限制器已初始化

                // local rate = hget redisson_rate_limiter rate
                // local interval = hget redisson_rate_limiter interval
                // local type = hget redisson_rate_limiter type
                // assert(rate != false and interval != false and type != false, 'RateLimiter is not initialized')
                "local rate = redis.call('hget', KEYS[1], 'rate');" + "local interval = redis.call('hget', KEYS[1], 'interval');" + "local type = redis.call('hget', KEYS[1], 'type');" + "assert(rate ~= false and interval ~= false and type ~= false, 'RateLimiter is not initialized')"

                        // 根据类型决定使用客户端还是全局许可值和许可名称
                        // local valueName   = {redisson_rate_limiter}:value
                        // local permitsName = {redisson_rate_limiter}:permits
                        // if (type.ordinal() == 1) then
                        //    valueName   = {redisson_rate_limiter}:value:client_id
                        //    permitsName = {redisson_rate_limiter}:permits:client_id
                        // end
                        + "local valueName = KEYS[2];" + "local permitsName = KEYS[4];" + "if type == '1' then " + "valueName = KEYS[3];" + "permitsName = KEYS[5];" + "end;"

                        // 确保请求的许可数量不超过定义的速率
                        // assert(tonumber(rate) >= tonumber(value), 'Requested permits amount could not exceed defined rate')
                        + "assert(tonumber(rate) >= tonumber(ARGV[1]), 'Requested permits amount could not exceed defined rate'); "

                        // 获取当前许可值
                        // local currentValue = get valueName;
                        // local res;
                        // if currentValue != false then
                        //    local expiredValues = zrangebysorce permitsName, 0, tonumber(System.currentTimeMillis()) - interval;
                        //    local released = 0;
                        //    for i,v in ipairs(expiredValues) do
                        //        local random, permits = struct.unpack('Bc0I', v);
                        //        realeased = released + permits;
                        //    end
                        //    if released > 0 then
                        //       zremrangebyscore permitsName, 0, tonumber(System.currentTimeMillis()) - interval;
                        //       if tonumber(currentValue) + released > tonumber(rate) then
                        //          currentValue = tonumber(rate) - zardcard permitsName;
                        //       else
                        //          currentValue = tonumber(currentValue) + released;
                        //       end
                        //       set valueName currentValue;
                        //    end
                        // 如果当前许可值足够，获取许可并更新Redis中的值
                        //    if tonumber(currentValue) < tonumber(value) then
                        //       local firstValue = zrange permitsName, 0, 0, withscores;
                        //       res = 3 + interval - (tonumber(System.currentTimeMillis()) - tonumber(firstValue[2]));
                        //    else
                        //       zadd permitsName, System.currentTimeMillis(), struct.pack('Bc0I', string.len(random), random, value);
                        //       decrby valueName, value;
                        //       res = null
                        //    end
                        // else
                        //     set valueName rate
                        //     zadd permitsName System.currentTimeMillis(), struct.pack('Bc0I', string.len(random), random, value);
                        //     decrby valueName value;
                        //     res = null
                        // end
                        // local ttl = pttl redisson_rate_limiter
                        // if (ttl > 0) then
                        //    pexpire valueName ttl
                        //    pexpire permitsName ttl
                        // end
                        // retrun res
                        + "local currentValue = redis.call('get', valueName); "
                        + "local res;"
                        + "if currentValue ~= false then "
                            + "local expiredValues = redis.call('zrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
                            + "local released = 0; "
                                + "for i, v in ipairs(expiredValues) do "
                                    + "local random, permits = struct.unpack('Bc0I', v);"
                                    + "released = released + permits;"
                                 + "end; "
                            + "if released > 0 then "
                                + "redis.call('zremrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
                                    + "if tonumber(currentValue) + released > tonumber(rate) then "
                                        + "currentValue = tonumber(rate) - redis.call('zcard', permitsName); "
                                    + "else "
                                        + "currentValue = tonumber(currentValue) + released; "
                                    + "end; "
                               + "redis.call('set', valueName, currentValue);"
                            + "end;"
                            + "if tonumber(currentValue) < tonumber(ARGV[1]) then "
                                + "local firstValue = redis.call('zrange', permitsName, 0, 0, 'withscores'); "
                                + "res = 3 + interval - (tonumber(ARGV[2]) - tonumber(firstValue[2]));"
                            + "else "
                                + "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
                                + "redis.call('decrby', valueName, ARGV[1]); " + "res = nil; " +
                            "end; "

                        + "else "
                            // 如果还没有许可值，初始化它并处理许可请求
                            + "redis.call('set', valueName, rate); "
                            + "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
                            + "redis.call('decrby', valueName, ARGV[1]); "
                            + "res = nil; "
                        + "end;"

                        // 更新许可值和许可名称的过期时间
                        + "local ttl = redis.call('pttl', KEYS[1]); "
                            + "if ttl > 0 then "
                                + "redis.call('pexpire', valueName, ttl); "
                                + "redis.call('pexpire', permitsName, ttl); "
                        + "end; "
                        + "return res;",
                // 提供Redis中相关键的列表和必要的参数
                Arrays.asList(getRawName(), getValueName(), getClientValueName(), getPermitsName(), getClientPermitsName()), value, System.currentTimeMillis(), random);
    }


    private static final RedisCommand HGETALL = new RedisCommand("HGETALL", new MapEntriesDecoder(new MultiDecoder<RateLimiterConfig>() {

        @Override
        public RateLimiterConfig decode(List<Object> parts, State state) {
            Map<String, String> map = new HashMap<>(parts.size() / 2);
            for (int i = 0; i < parts.size(); i++) {
                if (i % 2 != 0) {
                    map.put(parts.get(i - 1).toString(), parts.get(i).toString());
                }
            }

            if (map.size() == 0) {
                return new RateLimiterConfig(RateType.OVERALL, 0L, 0L);
            }
            RateType type = RateType.values()[Integer.parseInt(map.get("type"))];
            Long rateInterval = Long.valueOf(map.get("interval"));
            Long rate = Long.valueOf(map.get("rate"));
            return new RateLimiterConfig(type, rateInterval, rate);
        }

    }));

    @Override
    public RateLimiterConfig getConfig() {
        return get(getConfigAsync());
    }

    @Override
    public RFuture<RateLimiterConfig> getConfigAsync() {
        return commandExecutor.readAsync(getRawName(), StringCodec.INSTANCE, HGETALL, getRawName());
    }

    @Override
    public long availablePermits() {
        return get(availablePermitsAsync());
    }


    /**
     * 获取当前可用的许可数量
     */
    @Override
    public RFuture<Long> availablePermitsAsync() {
        return commandExecutor.evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_LONG,

                "local rate = redis.call('hget', KEYS[1], 'rate');"
                        + "local interval = redis.call('hget', KEYS[1], 'interval');"
                        + "local type = redis.call('hget', KEYS[1], 'type');"
                        + "assert(rate ~= false and interval ~= false and type ~= false, 'RateLimiter is not initialized')"

                        + "local valueName = KEYS[2];"
                        + "local permitsName = KEYS[4];" +
                        "if type == '1' then "
                           + "valueName = KEYS[3];"
                           + "permitsName = KEYS[5];"
                        + "end;"

                        + "local currentValue = redis.call('get', valueName); "
                        + "if currentValue == false then "
                            + "redis.call('set', valueName, rate); "
                            + "return rate; "
                        + "else "
                            + "local expiredValues = redis.call('zrangebyscore', permitsName, 0, tonumber(ARGV[1]) - interval); "
                            + "local released = 0; "
                            + "for i, v in ipairs(expiredValues) do "
                                + "local random, permits = struct.unpack('Bc0I', v);"
                                + "released = released + permits;"
                            + "end; "

                        + "if released > 0 then "
                            + "redis.call('zremrangebyscore', permitsName, 0, tonumber(ARGV[1]) - interval); "
                            + "currentValue = tonumber(currentValue) + released; "
                            + "redis.call('set', valueName, currentValue);"
                        + "end;"

                + "return currentValue; "
                + "end;",
                Arrays.asList(getRawName(), getValueName(), getClientValueName(), getPermitsName(), getClientPermitsName()), System.currentTimeMillis());
    }

    @Override
    public RFuture<Boolean> expireAsync(long timeToLive, TimeUnit timeUnit, String param, String... keys) {
        return super.expireAsync(timeToLive, timeUnit, param, getRawName(), getValueName(), getClientValueName(), getPermitsName(), getClientPermitsName());
    }

    @Override
    protected RFuture<Boolean> expireAtAsync(long timestamp, String param, String... keys) {
        return super.expireAtAsync(timestamp, param, getRawName(), getValueName(), getClientValueName(), getPermitsName(), getClientPermitsName());
    }

    @Override
    public RFuture<Boolean> clearExpireAsync() {
        return clearExpireAsync(getRawName(), getValueName(), getClientValueName(), getPermitsName(), getClientPermitsName());
    }

    @Override
    public RFuture<Boolean> deleteAsync() {
        return deleteAsync(getRawName(), getValueName(), getClientValueName(), getPermitsName(), getClientPermitsName());
    }

}
